package com.kgc.sbt.provider111;

import com.alibaba.dubbo.config.annotation.Service;
import com.kgc.sbt.api.SearchApi;
import com.kgc.sbt.beans.*;
import com.kgc.sbt.constant.SystemConstant;
import com.kgc.sbt.mapper.*;
import com.kgc.sbt.utils.PageSupportUtil;
import com.kgc.sbt.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * Created on 2021/8/16.
 * <p>
 * Author : Lcywings
 * <p>
 * Description :
 */
@Service
@Slf4j
public class SearchProvider implements SearchApi {

    @Autowired(required = false)
    private ProductMapper productMapper;

    @Autowired(required = false)
    private CommentMapper commentMapper;

    @Autowired(required = false)
    private ShopPictureMapper shopPictureMapper;

    @Autowired(required = false)
    private RotationChartMapper rotationChartMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired(required = false)
    private UserCollectMapper userCollectMapper;

    @Autowired(required = false)
    private UserTrackMapper userTrackMapper;

    @Autowired(required = false)
    private UserLoginMapper userLoginMapper;


//    @Autowired
//    private GoodsRepository goodsRepository;

    @Override
    public PageSupportUtil<Product> queryProductList(String keywords, Integer pageSize, Integer pageNo) {
//        log.info("productRepository.findOne(1):{}", productRepository.findOne(Long.valueOf(1)));
        log.info("------ 开始进行模糊查询，参数：{}，{}，{}", keywords, pageSize, pageNo);

        // 创建搜索对象
        ProductExample productExample = new ProductExample();
        ProductExample.Criteria criteria = productExample.createCriteria();

        // 创建分页对象
        PageSupportUtil<Product> pageSupportUtil = new PageSupportUtil<>();

        // 校验并传参（分页支持）
        if (pageSize < 1)
            pageSupportUtil.setPageSize(SystemConstant.SYS_INIT_PAGE_SIZE);
        else
            pageSupportUtil.setPageSize(pageSize);
        if (pageNo < 1)
            pageSupportUtil.setCurrPageNo(SystemConstant.SYS_INIT_PAGE_NO);
        else
            pageSupportUtil.setCurrPageNo(pageNo);

        // 设置模糊搜寻条件
        if (keywords != "") {
            criteria.andProductNameLike("%" + keywords + "%");
        }

        // 设置总条数
        pageSupportUtil.setTotalCount((int) productMapper.countByExample(productExample));

        // 设置分页
        productExample.setOrderByClause(" product_id ");
        productExample.setOffset((long) pageSupportUtil.getPageIndex());
        productExample.setLimit(pageSupportUtil.getPageSize());


        // 查询
        pageSupportUtil.setData(productMapper.selectByExample(productExample));

        log.info("------ 成功查询，结果：{}", pageSupportUtil);

        // 测试ES
//        log.info("瞧瞧能不能和世界说hi");
//        try {
//            Product product = productMapper.selectByPrimaryKey(1);
//            goodsRepository.save(product);
//            log.info("答案：{}",goodsRepository.findAll().toString());
//        } catch (Exception e) {
//            log.info("哦豁，完蛋");
//        }
//        log.info("Hi!!!!!!!!!");

        return pageSupportUtil;
    }

    @Override
    public ProductDetails queryProductDetails(String productId) {
        // 定义返回集合
        ProductDetails productDetails = new ProductDetails();

        // 定义评论、图片查询对象
        CommentExample commentExample = new CommentExample();
        ShopPictureExample shopPictureExample = new ShopPictureExample();
        CommentExample.Criteria commentCriteria = commentExample.createCriteria();
        ShopPictureExample.Criteria shopPictureCriteria = shopPictureExample.createCriteria();

        // 设置条件
        shopPictureCriteria.andProductIdEqualTo(Long.valueOf(productId));
        commentCriteria.andProductIdEqualTo(Integer.valueOf(productId));

        // 查询数据并设置返回集合
        Integer i = Integer.valueOf(productId);
        Product p = productMapper.selectByPrimaryKey(i);
        productDetails.setProduct(p);
        productDetails.setComments(commentMapper.selectByExample(commentExample));
        productDetails.setShopPictures(shopPictureMapper.selectByExample(shopPictureExample));

        return productDetails;
    }

    @Override
    public List<RotationChart> queryRotationCharts(Integer chartNo) {
        // 定义轮播图查询对象
        RotationChartExample rotationChartExample = new RotationChartExample();
        RotationChartExample.Criteria criteria = rotationChartExample.createCriteria();


        // 查询数据并设置返回集合
        return rotationChartMapper.selectByExample(rotationChartExample);
    }

    @Override
    public List<Product> queryCrowdFunding() {
        // 创建搜索对象
        ProductExample productExample = new ProductExample();
        ProductExample.Criteria criteria = productExample.createCriteria();

        // 设置限制条数
        productExample.setLimit(3);

        // 设置分类条件
        criteria.andFirstIdEqualTo("M1");

        return productMapper.selectByExample(productExample);
    }

    @Override
    public List<Product> querySecKill() {
        // 创建搜索对象
        ProductExample productExample = new ProductExample();
        ProductExample.Criteria criteria = productExample.createCriteria();

        // 设置限制条数
        productExample.setLimit(6);

        // 设置分类条件
        criteria.andFirstIdEqualTo("M2");

        return productMapper.selectByExample(productExample);
    }

    @Override
    public List<Product> queryDailyNew() {
        // 创建搜索对象
        ProductExample productExample = new ProductExample();
        ProductExample.Criteria criteria = productExample.createCriteria();

        // 设置限制条数
        productExample.setLimit(6);

        // 设置分类条件
        criteria.andFirstIdEqualTo("M3");

        return productMapper.selectByExample(productExample);
    }

    @Override
    public List<Product> queryVipRecommend(Integer userId) {
        if (userId == 0) {
            log.info("用户未登录，进行默认专属推荐");
            // 创建搜索对象
            ProductExample example = new ProductExample();
            ProductExample.Criteria criteria = example.createCriteria();

            // 设置分类条件
            criteria.andSecondIdEqualTo("C3");
            example.setLimit(12);

            return productMapper.selectByExample(example);
        }
        log.info("用户登录，进行用户专属推荐");
        // 创建搜索对象
        ProductExample productExample = new ProductExample();
        ProductExample.Criteria productCriteria = productExample.createCriteria();

        // 创建推荐对象搜索对象
        // 用户收藏
        UserCollectExample userCollectExample = new UserCollectExample();
        UserCollectExample.Criteria userCollectCriteria = userCollectExample.createCriteria();

        // 用户足迹
        UserTrackExample trackExample = new UserTrackExample();
        UserTrackExample.Criteria userTrackCriteria = trackExample.createCriteria();

        // 设置用户条件，按时间排序
        userCollectCriteria.andUserIdEqualTo(userId);
        userCollectExample.setOrderByClause(" collectTime desc ");
        userTrackCriteria.andUserIdEqualTo(userId);
        trackExample.setOrderByClause(" collectTime desc ");

        // 搜索用户最近收藏和浏览的货物id(如果用户没有收藏和足迹，就默认设置为1号商品)
        Integer cPId = 1;
        Integer tPId = 1;
        try {
            cPId = userCollectMapper.selectByExample(userCollectExample).get(0).getCommodityId();
            tPId = userTrackMapper.selectByExample(trackExample).get(0).getCommodityId();
        } catch (Exception e) {
            log.error("用户没有收藏或足迹！");
            e.printStackTrace();
        }

        // 根据找到的两个商品的id查分类(有可能是同一个商品,给设置默认为1，2号商品)
        productCriteria.andProductIdIn(Arrays.asList(cPId, tPId));
        String cId1 = "";
        String cId2 = "";
        try {
            cId1 = productMapper.selectByExample(productExample).get(0).getFirstId();
            cId2 = productMapper.selectByExample(productExample).get(1).getFirstId();
        } catch (Exception e) {
            log.error("收藏和足迹是同一个商品！");
            cId2 = cId1;
            e.printStackTrace();
        }

        // 创建搜索对象
        ProductExample example = new ProductExample();
        ProductExample.Criteria criteria = example.createCriteria();

        // 设置分类条件
        criteria.andFirstIdIn(Arrays.asList(cId1, cId2));
        example.setLimit(12);

        return productMapper.selectByExample(example);
    }

    @Override
    public List<Boolean> addCollect(Integer userId, Integer productId) {
        // 从数据库获取收藏状态
        UserCollectExample userCollectExample = new UserCollectExample();
        UserCollectExample.Criteria criteria = userCollectExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andCommodityIdEqualTo(productId);

        // 声明一个收藏对象，方便插入数据
        UserCollect userCollect = new UserCollect();
        userCollect.setUserId(userId);
        userCollect.setCommodityId(productId);
        userCollect.setCollectTime(new Date());

        // 判读是否已经收藏，并设置redis
        if (ObjectUtils.isEmpty(userCollectMapper.selectByExample(userCollectExample))) {
            // 如果没收藏，设置redis相应状态为0
            redisUtils.set(userId + "-" + productId + "-" + "collectState", 0);
        } else {
            // 如果已经收藏，设置redis相应状态为1，并且获取收藏信息
            redisUtils.set(userId + "-" + productId + "-" + "collectState", 1);
            List<UserCollect> userCollects = userCollectMapper.selectByExample(userCollectExample);
            userCollect.setCollectId(userCollects.get(0).getCollectId());
            userCollect.setUserId(userCollects.get(0).getUserId());
            userCollect.setCommodityId(userCollects.get(0).getCommodityId());
            userCollect.setCollectTime(userCollects.get(0).getCollectTime());
        }

        log.info("========================");
        log.info("点击收藏之前前状态：{}，", redisUtils.get(userId + "-" + productId + "-" + "collectState"));

        // 点击频率判断是否点击有效
        if (redisUtils.checkFreq("freq", 3, 5)) {
            // 如果是有效点击，判断是加入还是取消收藏
            if (redisUtils.get(userId + "-" + productId + "-" + "collectState").equals(0)) {
                // 加入收藏
                redisUtils.set(userId + "-" + productId + "-" + "collectState", 1);
                userCollectMapper.insert(userCollect);
                log.info("点击有效√，收藏成功√,收藏状态：{}", redisUtils.get(userId + "-" + productId + "-" + "collectState"));
                return Arrays.asList(true, true);
            } else {
                // 取消收藏
                redisUtils.set(userId + "-" + productId + "-" + "collectState", 0);
                // 查询收藏id进行删除
                userCollectMapper.deleteByPrimaryKey(userCollect.getCollectId());
                log.info("点击有效√，取消收藏X,收藏状态：{}", redisUtils.get(userId + "-" + productId + "-" + "collectState"));
                return Arrays.asList(true, false);
            }

        } else {
            log.info("点击无效X，收藏状态：{}", redisUtils.get(userId + "-" + productId + "-" + "collectState"));
            // 延时5s方可继续点击
            new Thread(() -> {
                try {
                    Thread.sleep(5000);
                    redisUtils.set("freq", 0);
                } catch (Exception e) {
                }
            }).start();
            return Arrays.asList(false, false);
        }
    }

    @Override
    public PageSupportUtil<UserCollectDetail> collectList(Integer userId, Integer pageSize, Integer pageNo) {
        log.info("进行收藏列表查询，参数：用户Id:{}，商品Id:{}，页面容量:{},当前页:{}", userId, pageSize, pageNo);

        // 创建搜索对象
        UserCollectExample userCollectExample = new UserCollectExample();
        UserCollectExample.Criteria criteria = userCollectExample.createCriteria();

        // 创建分页对象
        PageSupportUtil<UserCollectDetail> pageSupportUtil = new PageSupportUtil<>();

        // 校验并传参（分页支持）
        if (pageSize < 1)
            pageSupportUtil.setPageSize(SystemConstant.SYS_INIT_PAGE_SIZE);
        else
            pageSupportUtil.setPageSize(pageSize);
        if (pageNo < 1)
            pageSupportUtil.setCurrPageNo(SystemConstant.SYS_INIT_PAGE_NO);
        else
            pageSupportUtil.setCurrPageNo(pageNo);

        // 设置搜寻条件
        criteria.andUserIdEqualTo(userId);


        // 设置总条数
        try {
            pageSupportUtil.setTotalCount((int) userCollectMapper.countByExample(userCollectExample));

            // 设置分页
            userCollectExample.setOrderByClause(" collect_time desc ");
            userCollectExample.setOffset((long) pageSupportUtil.getPageIndex());
            userCollectExample.setLimit(pageSupportUtil.getPageSize());

            // 声明返回合集
            List<UserCollectDetail> udcs = new ArrayList<>();

            // 循环找商品详情
            List<UserCollect> userCollects = userCollectMapper.selectByExample(userCollectExample);
            for (int i = 0; i < userCollects.size(); i++) {
                UserCollectDetail ucd = new UserCollectDetail();
                ucd.setCollectId(userCollects.get(i).getCollectId());
                ucd.setCommodityId(userCollects.get(i).getCommodityId());
                ucd.setCollectTime(userCollects.get(i).getCollectTime());
                ucd.setUserId(userCollects.get(i).getUserId());
                ucd.setProduct(productMapper.selectByPrimaryKey(userCollects.get(i).getCommodityId()));
                udcs.add(ucd);
            }

            // 查询
            pageSupportUtil.setData(udcs);

        } catch (Exception e) {
            e.printStackTrace();
            return pageSupportUtil;
        }
        log.info("------ 成功查询，结果：{}", pageSupportUtil);

        return pageSupportUtil;
    }

    @Override
    public Integer selectUserIdByToken(String token) {
        log.info("拿到token：{}，去数据库查找userId", token);
        UserLoginExample userLoginExample = new UserLoginExample();
        userLoginExample.createCriteria().andTokenEqualTo(token);
        try {
            userLoginMapper.selectByExample(userLoginExample).get(0).getUserId();
            return userLoginMapper.selectByExample(userLoginExample).get(0).getUserId();
        } catch (Exception e) {
            e.printStackTrace();
            log.warn("token错误");
            return -1;
        }
    }

    @Override
    public Integer getProductIdByproductCode(String productCode) {
        log.info("拿到productCode：{}，去数据库查找productId", productCode);
        ProductExample productExample = new ProductExample();
        productExample.createCriteria().andProductCodeEqualTo(productCode);

        if (null == productMapper.selectByExample(productExample).get(0).getProductId()) {
            log.warn("productCode错误");
            return -1;
        }
        return productMapper.selectByExample(productExample).get(0).getProductId();
    }
}
